#!/bin/bash

# 检查输入参数
if [ $# -ne 1 ]; then
    echo "Usage: $0 <commit_id>" >&2
    exit 1
fi

commit_id="$1"
repo_path="$(pwd)/stash/linux"  # 持久化仓库路径
remote_url="https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git"
max_retries=1            # 最大重试次数

mkdir -p $(pwd)/stash

# 初始化仓库函数
init_repo() {
    # 首次克隆
    if [ ! -d "$repo_path/.git" ]; then
        echo "克隆仓库 git clone $remote_url $repo_path"
        git clone "$remote_url" "$repo_path" || return 1
    fi

    # 强制切换到master分支
    echo "切换到master分支"
    git -C "$repo_path" checkout master --force || return 1
}

# 更新仓库函数
update_repo() {
    echo "强制拉取仓库"
    git -C "$repo_path" pull --ff-only origin master || return 1
}

# 主验证函数
check_commit() {
    # 首次验证
    echo "验证commit" "$commit_id" "是否合法"
    if git -C "$repo_path" rev-parse --quiet --verify "$commit_id^{commit}"; then
        return 0
    fi

    # 重试逻辑
    for ((i=1; i<=$max_retries; i++)); do
        update_repo || return 1
        if git -C "$repo_path" rev-parse --quiet --verify "$commit_id^{commit}"; then
            echo "Found commit after update"
            return 0
        fi
    done

    return 1
}

# 执行初始化
if ! init_repo; then
    exit 1
fi

# 主检查流程
if ! check_commit; then
    echo "Error: Commit $commit_id not found after retries"
    exit 1
fi

# 提取mainline信息
mainline_commit=$(
    git -C "$repo_path" show -s --format=%B "$commit_id" | 
    sed -nE '
        s/.*[Uu]pstream[[:space:]]+commit[[:space:]]+([0-9a-f]{7,}).*/\1/p
        s/.*commit[[:space:]]+([0-9a-f]{7,})[[:space:]]+[Uu]pstream.*/\1/p
    ' |
    grep -m1 -E '^[0-9a-f]{7,}$'
)

[ -n "$mainline_commit" ] && echo "$mainline_commit" || echo "$commit_id"